package com.iot.service.mqtt.service.acl;

import com.iot.service.mqtt.config.Constant;
import io.netty.channel.Channel;
import io.netty.util.AttributeKey;

import java.util.List;

/**
 * @Author: hszhou
 * @Date: 2025/5/14 9:57
 * @Description: 必须描述类做什么事情, 实现什么功能
 */
public class FileAclValidator implements AclValidator {

    private final List<AclRule> rules;

    public FileAclValidator(List<AclRule> rules) {
        this.rules = rules;
    }


    private boolean matchesPrincipal(Channel channel, AclRule rule) {
        return switch (rule.getPrincipalType()) {
            case "user" -> channel.attr(AttributeKey.valueOf(Constant.USERNAME)).get() != null &&
                    rule.getPrincipals().contains(channel.attr(AttributeKey.valueOf(Constant.USERNAME)).get());
            case "client" ->
                    rule.getPrincipals().contains(channel.attr(AttributeKey.valueOf(Constant.CLIENT_ID)).get());
            case "ip" -> rule.getPrincipals().contains(channel.attr(AttributeKey.valueOf(Constant.IP)).get());
            case "*" -> true;
            default -> false;
        };
    }

    private boolean matchesAction(String action, AclRule rule) {
        return rule.getAction().equals("*") ||
                rule.getAction().equals(action);
    }

    @Override
    public boolean checkPermission(Channel ctx, String action, String topic) {
        for (AclRule rule : rules) {
            if (matchesPrincipal(ctx, rule) &&
                    matchesAction(action, rule) &&
                    AclConfigParser.matches(rule.getTopics(), topic)) {
                return rule.isAllow();
            }
        }
        return false; // 未匹配视为不通过
    }
}

